package com.wenyu.wenyuyuedu.activity.circle;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.wenyu.wenyuyuedu.R;
import com.wenyu.wenyuyuedu.adapter.PhotoAdapter;
import com.wenyu.wenyuyuedu.bean.circle.MyCreadeInvitationBean;
import com.wenyu.wenyuyuedu.utils.AbSharedUtil;
import com.wenyu.wenyuyuedu.utils.MyToast;
import com.wenyu.wenyuyuedu.utils.SharedConstants;
import com.wenyu.wenyuyuedu.utils.StatusBarUtil;
import com.wenyu.wenyuyuedu.utils.Xutils;

import org.xutils.common.Callback;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.InjectView;
import me.iwf.photopicker.PhotoPicker;
import me.iwf.photopicker.PhotoPreview;

/*
*圈子中发表动态
* */
public class MyCircleDeitalActivity extends AppCompatActivity implements View.OnClickListener {

    @InjectView(R.id.iv_public_left)
    ImageView ivPublicLeft;
    @InjectView(R.id.tv_public_title)
    TextView tvPublicTitle;
    @InjectView(R.id.my_circlename)
    TextView myCirclename;
    @InjectView(R.id.my_public_content)
    TextView myPublicContent;
    @InjectView(R.id.et_public_content)
    EditText etPublicContent;
    @InjectView(R.id.tv_public_sum)
    TextView tvPublicSum;
    @InjectView(R.id.tv_mycircle_residue)
    TextView tvMycircleResidue;
    @InjectView(R.id.tv_photo)
    ImageView tvPhoto;
    @InjectView(R.id.recycler_view)
    RecyclerView recyclerView;
    @InjectView(R.id.activity_my_circle_deital)
    LinearLayout activityMyCircleDeital;
    private Intent intent;
    /*圈子的id*/
    private String circleId;
    /*圈子的名字*/
    private String creatorName;
    private PhotoAdapter imageViewAdapter;
    private Context context;
    private String token;
    List<String> photos = null;
    private int code;
    private ProgressDialog dia;
    private FileOutputStream fos;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_circle_deital);
        StatusBarUtil.setStatusBar(MyCircleDeitalActivity.this, R.color.white);
        context = this;
        ButterKnife.inject(this);
        initView();

    }

    /*初始化跟布局的一些控件*/
    private void initView() {
        intent = getIntent();
        creatorName = intent.getStringExtra("creatorName");
        circleId = intent.getStringExtra("circleId");
        String circle_title = intent.getStringExtra("circle_title");
        myCirclename.setText(circle_title);
        ivPublicLeft.setOnClickListener(this);
        myPublicContent.setOnClickListener(this);
        tvPhoto.setOnClickListener(this);
        etPublicContent.addTextChangedListener(new MyEditTextChangeListener());
        imageViewAdapter = new PhotoAdapter(MyCircleDeitalActivity.this, selectedPhotos);

        recyclerView.setLayoutManager(new StaggeredGridLayoutManager(4, OrientationHelper.VERTICAL));
        recyclerView.setAdapter(imageViewAdapter);
        imageViewAdapter.setOnItemClickLisener(new PhotoAdapter.OnItemClickLisener() {
            @Override
            public void OnClick(View view, int position) {
                PhotoPreview.builder()
                        .setPhotos(selectedPhotos)
                        .setCurrentItem(position)
                        .start(MyCircleDeitalActivity.this);
            }
        });
    }

    /*编辑的监听*/
    class MyEditTextChangeListener implements TextWatcher {
        private CharSequence temp;

        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            temp = charSequence;
        }

        @Override
        public void afterTextChanged(Editable editable) {
            tvMycircleResidue.setText(temp.length() + "");
        }
    }

    private ArrayList<String> selectedPhotos = new ArrayList<>();

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK &&
                (requestCode == PhotoPicker.REQUEST_CODE || requestCode == PhotoPreview.REQUEST_CODE)) {

            if (data != null) {
                photos = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
            }
            selectedPhotos.clear();
            if (photos != null) {
                selectedPhotos.addAll(photos);
            }
            imageViewAdapter.notifyDataSetChanged();
        }
    }

    /*用来判断用户是否重复点击了上传图片的接口*/
    private int pageType = 0;

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            /*返回*/
            case R.id.iv_public_left:
                finish();
                break;
            /*发表*/
            case R.id.my_public_content:
                if (pageType == 0) {
                    dia = new ProgressDialog(this);
                    dia.setMessage("发布中，请稍后....");
                    dia.show();
                    pageType++;
                    token = AbSharedUtil.getString(MyCircleDeitalActivity.this, SharedConstants.USER_TOKEN);
                    String url = "http://www.iwenyu.cn/forum/circle/publishPost.html";
                    String etContent = etPublicContent.getText().toString().trim();
                    if (TextUtils.isEmpty(etContent) && photos == null) {
                        showPublicDialog();
                    } else {
                        Map<String, Object> map = new HashMap<>();
                        map.put("token", token);
                        map.put("id", circleId);
                        map.put("content", etContent);
                        if (photos != null) {
                            int size = photos.size();
                            for (int i = 0; i < size; i++) {
                                String s = photos.get(i);
                                Bitmap bitmap = BitmapFactory.decodeFile(s);
                                saveCroppedImage(bitmap, i);
                                bitmap.recycle();
                                File newFile = new File(newFilePath);
                                map.put("images" + i, newFile);
                            }
                        }
                        Xutils.UpLoadFile(url, map, new Callback.CommonCallback<String>() {
                            @Override
                            public void onSuccess(String result) {
                                Gson gson = new Gson();
                                MyCreadeInvitationBean myCreadeInvitationBean = gson.fromJson(result, MyCreadeInvitationBean.class);
                                code = myCreadeInvitationBean.getCode();
                                if (code == 1) {
                                    MyToast.showToast(MyCircleDeitalActivity.this, "发布成功", Toast.LENGTH_SHORT);
                                    finish();
                                    dia.dismiss();
                                    pageType = 0;
                                } else if (code == 3900) {
                                    MyToast.showToast(MyCircleDeitalActivity.this, "需要您登陆之后才可以查看的哦！", Toast.LENGTH_SHORT);
                                    dia.dismiss();
                                } else if (code == 3901) {
                                    MyToast.showToast(MyCircleDeitalActivity.this, "抱歉您的账户被暂时限制了，无法进行此操作", Toast.LENGTH_SHORT);
                                    dia.dismiss();
                                } else if (code == 3902) {
                                    MyToast.showToast(MyCircleDeitalActivity.this, "发动态的时候必须要有字符或者图片的!", Toast.LENGTH_SHORT);
                                    dia.dismiss();
                                } else if (code == 3903) {
                                    MyToast.showToast(MyCircleDeitalActivity.this, "发的动态的内容不能超过4000个字符!", Toast.LENGTH_SHORT);
                                    dia.dismiss();
                                } else if (code == 3904) {
                                    MyToast.showToast(MyCircleDeitalActivity.this, "图片格式不正确", Toast.LENGTH_SHORT);
                                    dia.dismiss();
                                } else if (code == 3905) {
                                    MyToast.showToast(MyCircleDeitalActivity.this, "系统繁忙，请稍后再试!", Toast.LENGTH_SHORT);
                                    dia.dismiss();
                                }

                            }

                            @Override
                            public void onError(Throwable ex, boolean isOnCallback) {
                                dia.dismiss();
                                pageType = 0;
                                MyToast.showToast(MyCircleDeitalActivity.this, "发布失败", Toast.LENGTH_SHORT);
                            }

                            @Override
                            public void onCancelled(CancelledException cex) {
                                dia.dismiss();
                                pageType = 0;
                                MyToast.showToast(MyCircleDeitalActivity.this, "发布取消", Toast.LENGTH_SHORT);
                            }

                            @Override
                            public void onFinished() {

                            }
                        });
                    }
                }
                break;
            /*选取照片*/
            case R.id.tv_photo:
                PhotoPicker.builder()
                        .setPhotoCount(9)
                        .setShowCamera(true)
                        .setSelected(selectedPhotos)
                        .start(this);
                break;
        }
    }

    AlertDialog ad;
    private TextView quxiao;
    private TextView queding;

    /*token错误或者已失效*/
    private void showPublicDialog() {
        ad = new AlertDialog.Builder(MyCircleDeitalActivity.this).create();
        ad.show();
        Window window = ad.getWindow();
        window.setContentView(R.layout.dailog_public);
        quxiao = (TextView) window.findViewById(R.id.dialog_login_quxiao);
        queding = (TextView) window.findViewById(R.id.dialog_login_queding);
        quxiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ad.dismiss();
                MyCircleDeitalActivity.this.finish();
            }
        });
        queding.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ad.dismiss();
            }
        });
    }

    private String newFilePath;

    /*压缩图片*/
    private void saveCroppedImage(Bitmap bmp, int position) {
        File file = new File("/sdcard/myFolder");
        if (!file.exists())
            file.mkdir();

        file = new File("/sdcard/temp.jpg".trim());
        String fileName = file.getName();
        String mName = fileName.substring(0, fileName.lastIndexOf("."));
        String sName = fileName.substring(fileName.lastIndexOf("."));
        //sdcard/myFolder/temp_cropped.jpg
        newFilePath = "/sdcard/myFolder" + "/" + mName + position + "_cropped" + sName;
        file = new File(newFilePath);
        Log.e("-nnnnn", newFilePath);
        try {
            file.createNewFile();
            fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 45, fos);
            fos.flush();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
